<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ title }}</span>
      </div>
      <div class="right">
        {{ $store.state.user.userInfo.userName }}
      </div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" :model="addForm" :rules="rules" label-width="100px">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in list"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item prop="businessLicenseId" label="营业执照">
              <el-upload ref="upload" action="#" :on-remove="removeFn" :http-request="uploadFile" :before-upload="beforeUpload">
                <el-button
                  :disabled="!!addForm.businessLicenseUrl"
                  size="small"
                  type="primary"
                  v-html="addForm.businessLicenseUrl ? '已上传' : '点击上传'"
                />
                <template
                  v-if="!addForm.businessLicenseUrl"
                  #tip
                  class="el-upload__tip"
                >只能上传jpg/png文件，且不超过500kb</template>
              </el-upload>
              <el-image v-if="addForm.businessLicenseUrl" :src="addForm.businessLicenseUrl" />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button :disabled="!!$route.params.id" @click="resetBtn">重置</el-button>
        <el-button type="primary" @click="confirmBtn">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { addCompanyAPI, editCompanyAPI, getCompanyDetailAPI, getIndustryListAPI, uploadFileAPI } from '@/api/park'

export default {
  data() {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: null, // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      rules: {
        name: [
          { required: true, message: '企业名称为必填', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '法人为必填', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '注册地址为必填', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '所在行业为必填', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '企业联系人为必填', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '企业联系人电话为必填', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        businessLicenseId: [
          { required: true, message: '请上传营业执照', trigger: 'blur' }
        ]
      },
      list: []
    }
  },
  computed: {
    title() {
      return this.$route.params.id ? '编辑企业' : '添加企业'
    }
  },
  created() {
    this.getIndustryList()
    if (this.$route.params.id) {
      this.getCompanyDetail()
    }
  },
  methods: {
    // 获取行业列表
    async getIndustryList() {
      const { data } = await getIndustryListAPI()
      this.list = data
    },
    // 文件校验
    beforeUpload(file) {
      const allowImgType = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        this.$message.error('上传合同图片只能是 PNG/JPG/JPEG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传合同图片大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    // 文件上传
    async uploadFile(value) {
      console.log(value)
      // 1. 根据接口要求，将数据更改为相应格式
      const fd = new FormData()
      fd.append('file', value.file)
      fd.append('type', 'businessLicense')
      // 2. 发送请求
      const { data } = await uploadFileAPI(fd)

      this.addForm.businessLicenseUrl = data.url
      this.addForm.businessLicenseId = data.id
      // 单独校验一次文件上传，以清除之前校验失败的报错
      // 因为el - form表单校验系统不能得到上传之后的通知，所以需要手动触发一次校验
      this.$refs.ruleForm.validateField('businessLicenseId')
      // 3. 提示用户
      this.$message.success('上传成功')
    },
    // 新增企业
    async confirmBtn() {
      // 1. 表单验证
      await this.$refs.ruleForm.validate()
      // 区分是新增还是编辑
      if (this.$route.params.id) {
        await editCompanyAPI(this.addForm)
        this.$message.success('编辑成功')
      } else {
        // 2. 发送请求
        await addCompanyAPI(this.addForm)
        // 3. 提示用户
        this.$message.success('新增企业成功')
      }
      // 4. 重置表单
      this.resetBtn()
      // 5. 跳转到企业管理页面
      this.$router.push('/park/enterprise')
    },
    // 获取企业详情
    async getCompanyDetail() {
      const res = await getCompanyDetailAPI(this.$route.params.id)
      console.log('企业详情获取成功', res)
      const { id, businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress } = res.data
      this.addForm = { id, businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress }
    },
    // 重置表单
    resetBtn() {
      this.$refs.ruleForm.resetFields()
      this.$refs.upload.clearFiles()
      this.addForm.businessLicenseUrl = ''
    },
    removeFn() {
      this.addForm.businessLicenseUrl = ''
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
